<template>
    <div>
        <Row>
            <Col span="12">
                <Table :columns="columnParent" :loading="Loading" :data="dataParent" id="test" :row-class-name="rowClassName"
                       @on-row-click="toggleTableExpand" highlight-row>
                    <template slot-scope="{row}" slot="action">
                        <Upload  :before-upload="beforeUpload" :accept="Accept"
                                action="/api/ac/hdplugin/ossService/uploadBase64">
                            <Button type="success" icon="ios-cloud-upload-outline" @click="uploadModal(row)"
                                    v-if="row.displayUpload==true" >上传要件</Button>
                        </Upload>
                    </template>
                </Table>
            </Col>
            <Col span="12"> <Table :columns="columnsSon"  :data="data" :loading="Loading2" :no-data-text="loadingText" >
                <template slot-scope="{ row }" slot="action">
                    <Button  type="error" v-if="isShowDeleteSs02005" @click="deleteSs02005(row)">删除</Button>
                    <Button style="margin-left: 10px" type="primary" @click="showSs02005(row)">查看</Button>
                    <Button style="margin-left: 10px"   @click="downloadSs02005(row)">下载</Button>
                </template>
            </Table></Col>
        </Row>
        <Modal v-model="visible" title="查看要件" width="700" style="position:relative;" >
            <img :src='imgUrl'  style=" width: auto; height: auto; max-width: 100%; max-height: 100%;  ">
        </Modal>
    </div>
</template>
<script>
    import {getAction, postAction} from '@/api/request'
    import {CommonMixin} from '@/views/common/js/CommonMixin'
    import '@/views/common/css/common.css';
    import DateFormat from '@/plugins/format.js'
    import { getSign, createUpLoadFiles,compressImg } from '@/api/common'
    export default {
        components: {},
        mixins: [CommonMixin],
        props: {
            ss11001Id: {
                type: String,
                required: false
            },
            ss12001Id: {
                type: String,
                required: false
            },
            //流程阶段code
            processPhase: {
                type: String,
                required: false
            },
            //展开并有权限节点
            expandedCode: {
                type: String,
                required: false
            },
            assistanceType: {
                type: String,
                required: false
            },
        },
        watch: {

            processPhase(newvalue, oldvalue) {
                if(newvalue!=undefined || newvalue !='') {
                    this.findSs11010List();
                }
            },
        },
        methods: {
            //table 点击行的事件
            toggleTableExpand(row, index) {
                var id = row.id; //获取父节点的id
                if(id !=undefined) {
                    this.tableData1.filter(item => {
                        //子节点的parentid = 选中的父节点id
                        if (item.parentId == id) {
                            //如折叠，则display= 显示
                            if (!row._expanded) {
                                item.display = "table-row";
                            } else {
                                //如展开，则display= 隐藏
                                item.display = "none";
                            }
                        }
                        //判断父节点，如选中的id = item.id ，前端页面table的属性：展开或折叠
                        if (item.id == id) {
                            item._expanded = !row._expanded;
                        }
                        //前端table 显示的table：dataParent数据= tableData1过滤掉=none
                        this.dataParent = this.tableData1.filter(item => item.display !== 'none');
                    });
                } else {
                    //判断是子节点的话，加载右侧要件项
                   this.findSs02005List(row.ss11010Id,row.ss02001Id);
                   //获取子节点的displayUpload, true: 右侧要件项table ss02005的 删除按钮隐藏，反之回显
                    if(row.displayUpload==true) {
                        this.isShowDeleteSs02005 = true;
                    } else {
                        this.isShowDeleteSs02005 = false;
                    }
                }
            },
            findSs02005List(yjfm0003,yjfm0004) {
                var that = this;
                that.Loading2 = true;
                postAction(that.url.findSs02005List, {yjfm0003: yjfm0003,yjfm0004: yjfm0004}).then((res) => {
                    if (res.data.errcode == 0) {
                        that.loadingText = '暂无数据';
                        that.data = res.data.data.data;
                        that.Loading2 = false;
                    } else {
                        that.$Message.error(res.data.errmsg);
                    }
                })
            },
            deleteSs02005(row){
                var that = this;
                this.$Modal.confirm({
                    title: '确定删除该要件吗？',
                    onOk: () => {
                        that.Loading2 = true;
                        postAction(this.url.deleteSs02005, {id: row.id}).then((res) => {
                            if (res.data.errcode == 0) {
                                that.$Message.success("删除成功!");
                                this.findSs02005List(this.ss11010Id,this.ss02001Id);
                                this.findSs11010List();
                            } else {
                                that.$Message.error(res.data.errmsg);
                            }
                            that.Loading2 = false;
                        })
                    }
                })
            },
            //查看要件
            showSs02005(row){
                this.visible =true;
                this.imgUrl = row.yjfm0002;
            },
            //下载要件
            downloadSs02005(row){
                this.downloadImage(row.yjfm0002, row.yjfm0001);
            },
            //table 行样式事件
            rowClassName (row, index) {
                if (row.ssbh0006 == '1') {
                    //异常状态：修改css
                    return 'demo-table-error-row';
                }
                return '';
            },
            uploadPositiveImg (type) {
                if (type === 'header') {
                    this.upPicData.fileName = DateFormat(new Date(), 'YYYYMMDDhhmmss') + '.png'
                }
                this.upPicData.filePath = 'subsistence/' + DateFormat(new Date(), 'YYYYMMDD') + '/'
            },
            beforeAvatarUpload (file) {
                return new Promise(() => {
                    compressImg(file, 200).then(res => {
                        let that = this
                        let index = res.indexOf('base64,') + 7
                        that.upPicData.file = res.substring(index)
                        that.upPic(that.upPicData)
                    })
                })
            },
            uploadModal(row){
                this.ss11010Id = row.ss11010Id;
                this.ss02001Id = row.ss02001Id;
            }
            , beforeUpload (file) {
                const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
                if (!isJpgOrPng) {
                  this.$Notice.error({ title: '上传失败', desc: '上传文件只能是 JPG 或 PNG 格式！' })
                  return false
                }
                let that = this
                this.upPicData.fileName = file.name;
                this.upPicData.filePath = 'subsistence/' + DateFormat(new Date(), 'YYYYMMDD') + '/';
                if (file.size / 1024 / 1024 > 1) { // 超过1M 压缩 图片为200K
                    return this.beforeAvatarUpload(file)
                }
                const reader = new FileReader()
                reader.readAsDataURL(file)
                reader.onload = () => {
                    let index = reader.result.indexOf('base64,') + 7
                    that.upPicData.file = reader.result.substring(index)
                    that.upPic(that.upPicData)
                }
                return false
            },
            upPic (obj) {
                var time = new Date().getTime()
                this.timeStep = time.toString()
                let param = {
                    filePath: obj.filePath,
                    fileName: obj.fileName,
                    timestamp: this.timeStep
                }
                param.fileName = this.uuid() + '.png'
                this.fileName = obj.fileName;
                this.Loading2 = true;
                getSign(param).then(res => {
                    if (res.data.errcode === 0) {
                        createUpLoadFiles('api/ac/subsistence/businessCommonService/upload', {
                            sign: res.data.data.sign,
                            timestamp: this.timeStep,
                            filePath: param.filePath,
                            fileName: param.fileName,
                            file: obj.file
                        }).then(res => {
                            if (res.data.errcode === 0) {
                                let hadoopBackUrl = res.data.data
                                //saveSs02005表
                                //ss11010id,ss02011id, fileName, hadoopBackUrl
                                let ss02005Param = {
                                    yjfm0001: this.fileName,
                                    yjfm0002: hadoopBackUrl,
                                    yjfm0003: this.ss11010Id,
                                    yjfm0004: this.ss02001Id
                                };
                                postAction(this.url.saveSs02005, ss02005Param).then((res) => {
                                    if (res.data.errcode == 0) {
                                        this.$Notice.info({ title: '上传文件成功', desc: "" })
                                        this.findSs11010List();
                                        this.findSs02005List(this.ss11010Id,this.ss02001Id);
                                    } else {
                                        that.$Message.error(res.data.errmsg);
                                    }
                                }).finally(() => {
                                    this.Loading2 = false;
                                });

                            } else {
                                this.$Notice.error({ title: '上传失败', desc: res.data.data.msg })
                            }
                        })
                    } else {
                        this.$Notice.error({ title: '上传失败', desc: res.data.data.msg })
                    }
                })
            },
            findSs11010List(){
                    this.Loading = true;
                    postAction(this.url.findSs11010List, {ss11001Id: this.ss11001Id,ss12001Id: this.ss12001Id,
                        processPhase:this.processPhase,expandedCode:this.expandedCode
                        ,assistanceType:this.assistanceType}).then((res) => {
                        if (res.data.errcode == 0) {
                            this.tableData1 = res.data.data.data;
                            this.dataParent = this.tableData1.filter(row => row.display !== 'none');
                            this.validateMsg = res.data.data.validateMsg;
                            this.validateCode = res.data.data.validateCode;
                            //回传给父组件
                            this.$emit("update:validateMsg", this.validateMsg)
                            this.$emit("update:validateCode", this.validateCode)
                            this.$emit("update:isDisabled", false)
                            this.Loading = false;
                        }
                    }).finally(() => {
                    });
            }
        },
        created() {
            //初始化table
            //processPhase : 默认 01
            //ss11001Id : ss11001Id
            //expandedCode 默认展开的节点
            this.findSs11010List();
        },
        data() {
            return {
                Accept: ".png,.jpg,.jpeg,.bpm",
                role_disabled:false,
                Loading: true,
                Loading2: false,
                isShowDeleteSs02005:false,
                loadingText: '暂无数据',
                validateMsg:'',
                validateCode:true,
                imgUrl:'',
                visible:false,
                fileName:'',
                ss11010Id:'',
                ss02001Id:'',
                upPicData: {},
                url: {
                    saveSs02005: "/api/ac/subsistence/ss11010Service/saveSs02005",
                    findSs11010List: "/api/ac/subsistence/ss11010Service/findSs11010List",
                    findSs02005List: "/api/ac/subsistence/ss11010Service/findSs02005List",
                    deleteSs02005: "/api/ac/subsistence/ss11010Service/deleteSs02005",
                },
                dataParent: [],
                tableData1: [
                ],
                columnParent: [
                    {
                        type: 'expand',
                        width: 50,
                    },
                    {
                        title: '要件名称',
                        key: 'ssbh0003'
                    },
                    {
                        title: '操作',
                        key: 'action',
                        align: 'center',
                        slot: 'action',
                    },
                ],
                columnsSon: [
                    {
                        type: 'index',
                        width: 60,
                        align: 'center'
                    },
                    {
                        title: '文件名称',
                        key: 'yjfm0001'
                    },{
                        title: '操作',
                        align: 'center',
                        slot: 'action',
                        className: 'nopadding',
                    }
                ],
                data: [],
            }
        }
    }
</script>
<style scoped>
    /deep/ #test tbody tr {
        display: none;
    }

    /deep/ #test tbody .ivu-table-row {
        display: table-row;
    }
</style>
